package com.example.demo.candycrush.strategy;

import com.example.demo.candycrush.model.ProcessResult;
/**
 * Stage 1
 */
public class ReplaceStrategy implements CrushStrategy {
    @Override
    public ProcessResult process(String input) {
        if (input == null || input.length() < 3) return null;
        
        for (int i = 0; i < input.length(); ) {
            int j = i + 1;
            while (j < input.length() && input.charAt(j) == input.charAt(i)) j++;
            
            if (j - i >= 3) {
                char c = input.charAt(i);
                String segment = input.substring(i, Math.min(i + 3, j));
                
                if (c == 'a') {
                    String newString = input.substring(0, i) + input.substring(j);
                    return new ProcessResult(newString, segment + " is removed");
                } else {
                    char replacement = (char) (c - 1);
                    String newString = input.substring(0, i) + replacement + input.substring(j);
                    return new ProcessResult(newString, segment + " is replaced by " + replacement);
                }
            } else {
                i = j;
            }
        }
        return null;
    }
}